|
|
|
|
|
|
|
The next several sections discuss basic assignment statements, mathematical operations, and strings. Later in the chapter, in the section "Formatting Results," you learn how to format numbers and other information manipulated by your program code. |
|
|
|
|
|
|
|
|
Using Assignment Statements |
|
|
|
|
|
|
|
|
After you declare a variable, the first thing you often need to do is to store information in the variable. This is the job of the assignment statement. The assignment statement is quite simple; you specify a variable whose value you want to set, place an equal sign after the variable name, and then follow it with the expression that represents the value you want stored. For example, the following line of code is the most basic type of assignment statement: |
|
|
|
|
|
|
|
|
The assignment statement tells Visual Basic to assign the integer value 5 to the space in memory represented by the variable x. Of course, you are not limited to assigning integer numbers. The expression following the equal sign can be a literal value, an expression or equation using some combination of other variables and constants, or even a function that returns a value. There is no limit on the complexity of the expression you can use. The only restriction is that the expression must yield a value of the same type as the variable to which it is assigned. |
|
|
|
|
|
|
|
|
Table 9.1 illustrates several assignment statements. |
|
|
|
|
| Table 9.1 Types of Assignment Statements | | Assignment Statement | Type of Expression | | nNumStudents = 25 | Numeric literal | | sTopStudent = "June Thomas" | String literal | | fAvgScore = nTotScore / nNumStudents | Mathematical expression | | sSpouseName = "Mrs. " & "Tina Fortner" | String expression | | sCapitalName = UCase$("Chris Cawein") | Return value of a function |
|
|
|
|
|
|
You might have noticed that these statements look similar to the ones used to set the properties of forms and controls in the section "Referencing Forms and Controls from Your Code" in Chapter 3, "Visual Basic Building Blocks." Actually, they are the same. Most properties of forms and controls act like variables. They can be set at design time but can also be changed at runtime using an assignment statement. |
|
|
|
|
|
|
|
|
You use a control property on the right side of a statement to assign its value to a variable for further processing or on the left side to change the value of the property. For example, suppose you have three text boxes on a form: txtLastname, txtFirstName, and txtEntireName. As a user types in the first or last name, automatically populating the txtEntireName box would be nice. One way to accomplish this feat would be to first store the information from each text box in a variable, as follows: |
|
|
|
|
|